$ErrorActionPreference = 'Stop'

function Has-StagedTmdbChanges {
    $names = git diff --cached --name-only | Where-Object { $_ -like 'data/tmdb/json/*' }
    return ($names -ne $null -and $names.Count -gt 0)
}

function Commit-And-Push($message) {
    if (Has-StagedTmdbChanges) {
        git commit -m $message | Out-Host
        git push origin main | Out-Host
    }
}

Write-Host 'Batch pushing TMDB JSON in two-digit prefix groups (00..99)...'
for ($i = 0; $i -le 9; $i++) {
    for ($j = 0; $j -le 9; $j++) {
        $prefix = "$i$j"
        $pattern = "data/tmdb/json/$prefix*.json"
        $files = Get-ChildItem -ErrorAction SilentlyContinue -File $pattern
        if ($files) {
            Write-Host "Staging prefix $prefix* ($($files.Count) files)"
            git add $pattern 2>$null | Out-Null
            Commit-And-Push "data-tmdb: add TMDB JSON batch prefix $prefix* via LFS"
        }
    }
}

# Handle single-digit files like 0.json..9.json
$singlePattern = 'data/tmdb/json/?.json'
$singleFiles = Get-ChildItem -ErrorAction SilentlyContinue -File $singlePattern
if ($singleFiles) {
    Write-Host "Staging single-digit files ($($singleFiles.Count) files)"
    git add $singlePattern 2>$null | Out-Null
    Commit-And-Push 'data-tmdb: add TMDB JSON batch single-digit via LFS'
}

Write-Host 'Done. If there are still remaining files, re-run the script or narrow the prefix.'
